<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Templates_model extends CI_Model {

	private $table = "foria_templates";

    function __construct()
    {
        parent::__construct();

		$this->tree_params = array (
			'table'		=> $this->table,
			'id_node_name' => 'templates',
			'id'		=> 'id',
			'parent_id'	=> 'parent_id',
			'position'	=> 'position',
			'level'		=> 'level',
		);

		$this->name_fields = array (
			'name'
		);
		$this->load->library('Treeclass', $this->tree_params);
		$this->load->library('Transaction', array ('tr_table'=>'foria_templates'));
    }

    public function load_tree()
	{
		$id = (int)$_POST['id'];
		return $this->treeclass->_to_json($id, $this->name_fields);
	}

	public function move_tree()
	{
		$id = (int)$_GET['id'];
		$ref = (int)$_GET['ref'];
		$position = (int)$_GET['position'];
		$copy = (int)$_GET['copy'];
		$ret = array (
			'status' => 0
		);
		$id      = $this->treeclass->move_node($id, $ref, $position, $copy);
		$node    = $this->treeclass->fetch_data($id, array('name', 'position'));
		$nchilds = $this->treeclass->count_childs($id);
		if ($id)
		{
			$ret['status'] = 1;
			$ret['id'] = $id;
			$data = array (
				'action'=>'move',
				'id'=>$id,
				'ref'=>$ref,
				'position'=>$node['position'],
				'copy'=>$copy,
				'name'=>$node['name'],
			);
			if ($nchilds>0)
			{
				$data['state']='closed';
			}
			$this->transaction->insert('move', $id, json_encode($data));
		}
		return json_encode($ret);
	}

	public function load () {
		$id = (int)$_POST['id'];
		$data = array ();
		$this->db->where('id', $id);
		$this->db->select('*');
		$query = $this->db->get($this->table);
		if ($row = $query->result_array())
		{
			$data = $row[0];
			$data['error'] = '';
		} else {
			$data['error'] = 'Не могу прочитать шаблон с указаным ИД='.$id;
		}
		return json_encode($data);
	}

	private function _is_exists ($a_where)
	{
		$this->db->where($a_where);
		$this->db->select('name');
		$query = $this->db->get($this->table);
		if ($query->num_rows() > 0)
			return true;
		return false;
	}

	public function create()
	{
		/* сюда в будущем нужно вставить проверку на допустимость */
		$position = (int)$_POST['position'];
		$name = $_POST['name'];
		$_POST['subpage'] == 'false'?$id=0:$id = (int)$_POST['id'];
		$ret = array (
			'status' => 0,
			'error' => ''
		);
		if (empty($name))
		{
			$ret['error'] = 'Имя шаблона пустое';
			return $ret;
		}
/*
		if ($this->_is_exists(array ('id' => $id))==false) {
			$ret['error'] = 'Не куда присоеденить страницу. Выберете узел для присоединения и попробуйте снова.';
			return $ret;
		}
*/
		if ($this->_is_exists(array ('name' => $name, 'parent_id' => $id))==true) {
			$ret['error'] = 'Обнаружен дубликат.';
			return $ret;
		}
		// будем считать что страницу мы всегда добавляем в текущий узел
		$nid = $this->treeclass->append_node($id, 0);

		if ($nid)
		{
			$data = array (
				'name' => $name,
				'content' => 'Шаблон - '.$name
			);
			$this->treeclass->set_data($nid, $data);
			$ret['status'] = 1;
			$ret['id'] = $nid;
			$ret['position'] = $this->treeclass->get_node_position($nid);
			$data = array (
				'action'=>'new',
				'pid'=>$id,
				'name'=>$name,
				'id'=>$nid,
				'position'=>$ret['position']
			);
			$this->transaction->insert('new', $nid, json_encode($data));
		}

		return json_encode($ret);

	}

	public function delete()
	{
		/* сюда в будущем нужно вставить проверку на допустимость */
		$id = (int)$_POST['id'];
		$ret = array (
			'status' => 0
		);
		if ($this->treeclass->delete_node($id, true))
		{
			$ret['status']=1;
			$data = array (
				'action'=>'del',
				'id'=>$id
			);
			$this->transaction->insert('del', $id, json_encode($data));
		}
		return json_encode($ret);
	}

	public function save()
	{
		/* сюда в будущем нужно вставить проверку на допустимость */
		$ret = array();
		$id = (int)$_POST['id'];
		$data = array(
			'content' => $_POST['content'],
			'name' => $_POST['name'],
			'main' => $_POST['main'],
			'modified' => $this->transaction->mtime
		);
		$this->treeclass->set_data($id, $data);
		$data = array (
			'action'=>'save',
			'id'=>$id,
			'name' => $_POST['name']
		);

		/* check template for an error and return line and error message to editor */
		$this->load->library('Smartyclass');
		$ret['compile'] = $this->smartyclass->checkTemplate($_POST['content']);

		$this->transaction->insert('save', $id, json_encode($data));
		$ret['error'] = '';
		return json_encode($ret);
	}

	public function fetch_tree_changes()
	{
		$lmtime = $_GET['templates_last_access'];
		$data = $this->transaction->fetch($lmtime);
		$ret = array (
			'data'=>$data,
			'templates_last_access' => $this->transaction->mtime
		);

		return json_encode($ret);

	}

	private function _fetch_templates (&$data, $parent_id = 0, $parent_name = "")
	{
		$this->db->where('parent_id', $parent_id);
		$this->db->where('main', 'true');
		$this->db->order_by('position');
		$this->db->select('id, name');
		$query = $this->db->get($this->table);
		if ($query->num_rows()>0)
		{
			foreach ($query->result_array() as $row) {
				$name = $row['name'];
				if ($parent_id > 0)
				{
					$name = $parent_name."/".$name;
				}
				$data[] = $name;
				$this->_fetch_templates ($data, $row['id'], $name);
			}
		}
	}


	public function fetch_templates ()
	{
		$data = array();
		$this->_fetch_templates ($data, 0, "");
		return $data;
		//print_r ($data);
		//exit;
	}

}